import http from '@ohos.net.http';
import Food from '../modle/Food';
import PreferenceUtil from './PreferencesUtil'
import { preferences } from '@kit.ArkData';
import LoginResponse from '../modle/LoginResponse';
import OrderBean from '../modle/OrderBean';
import Toast from './Toast';

class ApiUtil {
  private httpRequest = http.createHttp();
  // private baseUrl = "http://127.0.0.1:8080/";
  //这里填入你电脑的IP地址，windows使用命令ipconfig查看
  private baseUrl = "http://172.20.10.9:8081/";

  private doPost(
    path: string,
    paramsObj: object,
    sucessCallBack: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.httpRequest.request(
      this.baseUrl + path,
      {
        method: http.RequestMethod.POST,
        header: {
          'Content-Type': 'application/json'
        },
        // 对于 POST 请求，可以添加请求体
        extraData: JSON.stringify(paramsObj)
      }, (err, data) => {
      endCallBack?.()
      if (!err) {
        let resStr = data.result.toString()
        let resObj = data.result
        console.info("zhu post Request success, data: " + resStr);
        sucessCallBack(resObj)
      } else {
        console.error("zhu post Request failed, error: " + JSON.stringify(err));
        Toast.show('post请求错误=' + err.message)
      }
    }
    );
  }

  private doGet(
    path: string,
    paramsObj: object,
    sucessCallBack: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.httpRequest.request(
      this.baseUrl + path,
      {
        method: http.RequestMethod.GET,
        header: {
          'Content-Type': 'application/json'
        },
        // 对于 POST 请求，可以添加请求体
        extraData: JSON.stringify(paramsObj)
      }, (err, data) => {
      endCallBack?.()
      if (!err) {
        let resStr = data.result.toString()
        let resObj = data.result
        console.info("zhu get Request success, data: " + resStr);
        sucessCallBack(resObj)
      } else {
        console.error("zhu get Request failed, error: " + JSON.stringify(err));
        Toast.show('get请求错误=' + err.message)
      }
    }
    );
  }

  public login(
    paramsObj: object,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('user_info/login', paramsObj, (res: Object) => {
      try {
        console.info("zhu login success, data: " + res);
        let obj: any = JSON.parse(res.toString())
        let id = obj.userInfo.id
        PreferenceUtil.putPreferenceValue('user_id', id)
        callback(res)
      } catch (e) {
        console.error("zhu login catch, e= " + e);
      }
    }, endCallBack)
  }

  public sendVerificationCode(phoneNumber: string, callback: () => void) {
    this.doPost('user_info/sendCode', { user_name: phoneNumber }, (res: any) => {
      callback();
    });
  }

  public resetPassword(
    paramsObj: object,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('user_info/resetPassword', paramsObj, (res: Object) => {
      console.info("zhu resetPassword success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public register(
    paramsObj: object,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('user_info/regist', paramsObj, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public getHomeData(
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doGet('home_data/get', null, (res: Object) => {
      try {
        console.info("zhu home success, data: " + res);
        callback(res)
      } catch (e) {
        console.error("zhu home catch, e= " + e);
      }
    }, endCallBack)
  }

  public getCateList(
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doGet('cate_list/get', null, (res: Object) => {
      try {
        console.info("zhu getCateList success, data: " + res);
        callback(res)
      } catch (e) {
        console.error("zhu getCateList catch, e= " + e);
      }
    }, endCallBack)
  }

  public async cartAdd(
    paramsObj: Food,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    let v2: preferences.ValueType = await PreferenceUtil.getPreferenceValue('user_id', '')
    paramsObj.user_id = v2 as number
    this.doPost('cart/add', paramsObj, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public cartDelete(
    id: number,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('cart/delete', {
      id: id
    }, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public cartBatchDelete(
    idList: number[],
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('cart/batchDelete', {
      idList: idList
    }, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public async cartQueryAll(
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    let v2: preferences.ValueType = await PreferenceUtil.getPreferenceValue('user_id', '')
    let user_id = v2 as number
    this.doPost('cart/queryAll', {
      user_id: user_id
    }, (res: Object) => {
      console.info("zhu cartQueryAll success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public payOrder(
    id: number,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('order/pay', {
      id: id
    }, (res: Object) => {
      console.info("zhu payOrder success, data: " + res);
      callback(res);
      // 在这里更新界面，移除已支付的商品
    }, endCallBack);
  }

  public placeOrder(
    id: number,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('cart/order', {
      id: id
    }, (res: Object) => {
      console.info("zhu placeOrder success, data: " + res);
      callback(res);
      // 在这里更新界面，移除已下单的商品
    }, endCallBack);
  }

  public async orderAdd(
    paramsObj: OrderBean,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    let v2: preferences.ValueType = await PreferenceUtil.getPreferenceValue('user_id', '')
    paramsObj.user_id = v2 as number
    this.doPost('order/add', paramsObj, async (res: Object) => {
      console.info("zhu orderAdd success, data: " + res);
      try {
        const responseData = JSON.parse(JSON.stringify(res));
        if (responseData.code === 1) {
          // 下单成功后，更新本地订单数据
          await this.refreshOrderList();
          callback(res);
        } else {
          console.error("orderAdd failed: " + responseData.msg);
          callback(res);
        }
      } catch (e) {
        console.error("Error parsing orderAdd response: " + e);
        callback(res);
      }
    }, endCallBack)
  }

  public async orderQueryAll(
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    let v2: preferences.ValueType = await PreferenceUtil.getPreferenceValue('user_id', '')
    let user_id = v2 as number
    this.doPost('order/queryAll', {
      user_id: user_id
    }, (res: Object) => {
      console.info("zhu cartQueryAll success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public async orderQueryById(
    id: number,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('order/queryById', {
      id: id
    }, (res: Object) => {
      console.info("zhu orderQueryById success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public orderDelete(
    id: number,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('order/delete', {
      id: id
    }, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public orderUpdate(
    req: { id: string; state: number },
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('order/updateState', req, async (res: Object) => {
      console.info("zhu orderUpdate success, data: " + res);
      try {
        const responseData = JSON.parse(JSON.stringify(res));
        if (responseData.code === 1) {
          // 支付成功后，更新本地订单数据
          await this.refreshOrderList();
          callback(res);
        } else {
          console.error("orderUpdate failed: " + responseData.msg);
          callback(res);
        }
      } catch (e) {
        console.error("Error parsing orderUpdate response: " + e);
        callback(res);
      }
    }, endCallBack)
  }


  private async refreshOrderList() {
    return new Promise((resolve) => {
      this.orderQueryAll((orderList) => {
        // 这里可以将订单列表存储到本地缓存或更新页面显示
        console.log("Refreshed order list: ", orderList);
        resolve(orderList);
      });
    });
  }
}

let apiUtil = new ApiUtil()

export default apiUtil as ApiUtil